<?php

namespace app\console\model;

use app\client\model\ShopSpecAttr as ShopSpecAttrModel;
use app\client\model\ShopGoodsType as ShopGoodsTypeModel;
use app\client\model\Shop as ShopModel;
use think\Request;
use think\Model;
use think\Session;

class ShopGoods extends Model
{

    // 审核状态
    protected function getStatusTextAttr($value, $data)
    {
        $status = [1 => '审核成功', 2 => '等待审核', 3 => '违规下架'];
        return $status[$data['status']];
    }

    // 栏目名称
    protected function getShopParenTextAttr($value, $data)
    {
        $ShopParenText = ShopGoodsTypeModel::where(['id' => $data['parenTid']])->value('title');

        return $ShopParenText;
    }

    // 模型事件
    protected static function init()
    {
        // 写入前
        self::event('before_write', function ($data) {
            $data->create_time = strtotime(Request::instance()->param('create_time'));               // 创建时间
            $data->date_time = date('m月d日', strtotime(Request::instance()->param('create_time')));  // 创建时间（时间格式）
            $data->rebate_percentage = ShopModel::where(['member_id' => Session::get('shop_id')])->value('rebate_percentage');               // 创建时间
            $data->picUrl = uploadImg();
            // 图片
            $data->thumb_img = show_thumb_pic($data->picUrl);                                         // 缩略图
            $data->picArr = serialize(Request::instance()->param('picArr/a'));// 组图
            if(Request::instance()->action() == 'create'){
                $data->goods_attr = serialize(Request::instance()->param('sp_val/a'));
            }else{

            }
                   // 属性规格

            $data->goods_title = str_replace(' ', '', Request::instance()->param('goods_title'));    // 编辑标题方法
            $data->goods_str = parentStr(Request::instance()->param('goods_id'), 'goods_type');      // parenStr方法(平台)
            $data->parentStr = parentStr(Request::instance()->param('parenTid'), 'shop_goods_type'); // parenStr方法
            $data->update_time = time();


        });

        self::event('before_insert',function ($data){
            $data->activity = 2;
        });

        // 写入后
        self::event('after_write', function ($data) {

            $spec = Request::instance()->param('spec/a');
            $id = Request::instance()->param('id');
            if (!empty($spec)) {

                // 先清空sku关联表
                if (empty($id)) {
                    // ShopSpecAttrModel::destroy(['goods_id' => $id]);
                    $id = $data->id;
                }

                $information = '';
                // 添加sku关联表
                foreach ($spec as $key => $value) {

                    if (empty($value['id'])) {

                        $information[] = [
                            'goods_id'       => $id,
                            'attribute_id'   => $key,
                            'attribute'      => implode(',', $value['sp_value']),
                            'attr'           => serialize($value['sp_value']),
                            'market_price'   => $value['marketprice'],
                            'price'          => $value['price'],
                            'inventory'      => $value['stock'],
                            'inventory_hint' => $value['alarm'],
                            'style_id'       => $value['sku']
                        ];

                    } else {

                        $information[] = [
                            'id'             => $value['id'],
                            'goods_id'       => $id,
                            'attribute_id'   => $key,
                            'attribute'      => implode(',', $value['sp_value']),
                            'attr'           => serialize($value['sp_value']),
                            'market_price'   => $value['marketprice'],
                            'price'          => $value['price'],
                            'inventory'      => $value['stock'],
                            'inventory_hint' => $value['alarm'],
                            'style_id'       => $value['sku']
                        ];

                    }


                }

                (new ShopSpecAttrModel())->saveAll($information);
            }
        });
    }

    public function shopSpecAttr()
    {
        return $this->hasMany('ShopSpecAttr', 'goods_id', 'id');
    }

    public function flagAttr()
    {
        return $this->hasMany('ShopGoodsFlag', 'goods_id', 'id');
    }
}
